
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Component," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>属性传递 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        属性传递
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Component/" rel="tag">Ember-Component</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 2 分钟</span>
    </header>

    <div class="post-content">
      <h2 id="1，传递参数到组件上"><a href="#1，传递参数到组件上" class="headerlink" title="1，传递参数到组件上"></a>1，传递参数到组件上</h2><p>每个组件都是相对独立的，因此任何组件所需的数据都需要通过组件的属性把数据传递到组件中。</p>
<p>比如上篇<a href="http://xcoding.tech/2018/08/04/ember-teach/components/%E7%BB%84%E4%BB%B6%E5%AE%9A%E4%B9%89/">Ember.js 入门指南之二十八组件定义</a>的第三点<code>{{component item.pn post=item}}</code>就是通过属性post把数据传递到组件<code>foo-component</code>或者<code>bar-component</code>上。如果在<code>index.hbs</code>中是如下方式调用组件那么渲染之后的页面是空的。<br><code>{{component item.pn}}</code><br>请读者自己修改<code>index.hbs</code>的代码后演示效果。</p>
<p>传递到组件的参数也是动态更新的，当传递到组件上的参数变化时组件渲染的HTML也会随之发生改变。</p>
<h4 id="2，位置参数"><a href="#2，位置参数" class="headerlink" title="2，位置参数"></a>2，位置参数</h4><p>传递的属性参数不一定要指定参数的名字。你可以不指定属性参数的名称，然后根据参数的位置获取对应的值，但是要在组件对应的组件类中指定位置参数的名称。比如下面的代码：</p>
<p>准备工作：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ember g route passing-properties-to-component</span><br><span class="line"></span><br><span class="line">ember g component passing-properties-to-component</span><br></pre></td></tr></table></figure>

<p>调用组件的模板，传入两个位置参数，分别是item.title、item.body。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/passing-properties-to-component.hbs  --&gt;</span></span><br><span class="line"> </span><br><span class="line">&#123;&#123;#each model as |item|&#125;&#125;</span><br><span class="line">       <span class="comment">&lt;!-- 传递到组件blog-post第一个参数为数据的title值，第二个为body值 --&gt;</span></span><br><span class="line">       &#123;&#123;passing-properties-to-component item.title item.body&#125;&#125;</span><br><span class="line">&#123;&#123;/each&#125;&#125;</span><br></pre></td></tr></table></figure>



<p>准备需要显示的数据。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/routes/padding-properties-to-component.js</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Route.extend(&#123;</span><br><span class="line"> </span><br><span class="line">       model: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> [</span><br><span class="line">                 &#123; <span class="attr">id</span>: <span class="number">1</span>, <span class="attr">title</span>: <span class="string">&#x27;Bower: dependencies and resolutions new&#x27;</span>, <span class="attr">body</span>: <span class="string">&quot;In the bower.json file, I see 2 keys dependencies and resolutionsWhy is that so? &quot;</span> &#125;,</span><br><span class="line">                 &#123; <span class="attr">id</span>: <span class="number">2</span>, <span class="attr">title</span>: <span class="string">&#x27;Highly Nested JSON Payload - hasMany error&#x27;</span>, <span class="attr">body</span>: <span class="string">&quot;Welcome to the Ember.js discussion forum. We&#x27;re running on the open source, Ember.js-powered Discourse forum software. &quot;</span> &#125;,</span><br><span class="line">                 &#123; <span class="attr">id</span>: <span class="number">3</span>, <span class="attr">title</span>: <span class="string">&#x27;Passing a jwt to my REST adapter new &#x27;</span>, <span class="attr">body</span>: <span class="string">&quot;This sets up a binding between the category query param in the URL, and the category property on controller:articles. &quot;</span> &#125;</span><br><span class="line">           ];</span><br><span class="line">         </span><br><span class="line">       &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>在组件类中指定位置参数的名称。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/components/padding-properties-to-component.js</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Component.extend(&#123;</span><br><span class="line">       <span class="comment">// 指定位置参数的名称</span></span><br><span class="line">       positionalParams: [<span class="string">&#x27;title&#x27;</span>, <span class="string">&#x27;body&#x27;</span>]</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong>属性positionalParams指定的参数不能在运行期改变。</p>
<p>组件直接使用组件类中指定的位置参数名称获取数据。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  app/templates/components/passing-properties-to-component.hbs  --&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">article</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">h1</span>&gt;</span>&#123;&#123;title&#125;&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123;body&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">article</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong>获取数据的名称必须要与组件类指定的名称一致，否则无法正确获取数据。</p>
<p>显示结果如下：</p>
<p> <img src="http://static.oschina.net/uploads/space/2015/1009/234249_uzqI_565401.png"></p>
<p>       Ember还允许你指定任意多个参数，但是组件类获取参数的方式就需要做点小修改。比如下面的例子：</p>
<p>调用组件的模板</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/passing-properties-to-component.hbs  --&gt;</span></span><br><span class="line"> </span><br><span class="line">&#123;&#123;#each model as |item|&#125;&#125;</span><br><span class="line">       <span class="comment">&lt;!-- 传递到组件blog-post第一个参数为数据的title值，第二个为body值 --&gt;</span></span><br><span class="line">       &#123;&#123;passing-properties-to-component item.title item.body &#x27;third value&#x27; &#x27;fourth value&#x27;&#125;&#125;</span><br><span class="line">&#123;&#123;/each&#125;&#125;</span><br></pre></td></tr></table></figure>

<p>指定参数名称的组件类，获取参数的方式可以参考<a target="_blank" rel="noopener" href="http://ibeginner.sinaapp.com/index.php?m=Home&c=Index&a=detail&id=99fdb00c49afb32174c4f189c60382d6">计算属性</a>这章。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/components/padding-properties-to-component.js</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Component.extend(&#123;</span><br><span class="line">       <span class="comment">// 指定位置参数为参数数组</span></span><br><span class="line">       positionalParams: <span class="string">&#x27;params&#x27;</span>,</span><br><span class="line">       title: Ember.computed(<span class="string">&#x27;params.[]&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">              <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;params&#x27;</span>)[<span class="number">0</span>];  <span class="comment">//获取第一个参数</span></span><br><span class="line">       &#125;),</span><br><span class="line">       body: Ember.computed(<span class="string">&#x27;params.[]&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">              <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;params&#x27;</span>)[<span class="number">1</span>];  <span class="comment">//获取第二个参数</span></span><br><span class="line">       &#125;),</span><br><span class="line">       third: Ember.computed(<span class="string">&#x27;params.[]&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">              <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;params&#x27;</span>)[<span class="number">2</span>];  <span class="comment">//获取第三个参数</span></span><br><span class="line">       &#125;),</span><br><span class="line">       fourth: Ember.computed(<span class="string">&#x27;params.[]&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">              <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;params&#x27;</span>)[<span class="number">3</span>];  <span class="comment">//获取第四个参数</span></span><br><span class="line">       &#125;)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>下面看组件是怎么获取传递过来的参数的。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  app/templates/components/passing-properties-to-component.hbs  --&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">article</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">h1</span>&gt;</span>&#123;&#123;title&#125;&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123;body&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>third: &#123;&#123;third&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>fourth: &#123;&#123;fourth&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">article</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>显示结果如下：</p>
<p> <img src="http://static.oschina.net/uploads/space/2015/1009/234309_BMUy_565401.png"></p>
<p>到此组件参数传递的内容全部介绍完毕。总的来说没啥难度。Ember中参数的传递与获取方式基本是相似的，比如<a href="http://xcoding.tech/2018/08/04/ember-teach/templetes/link-to%20helper/">link-to助手</a>、<a href="http://xcoding.tech/2018/08/04/ember-teach/templetes/action%20helper/">action助手</a>。</p>
<p>br<br>博文完整代码放在<a href="httpsgithub.comubuntuvimmy_emberjs_code">Github</a>（博文经过多次修改，博文上的代码与github代码可能有出入，不过影响不大！），如果你觉得博文对你有点用，请在github项目上给我点个<code>star</code>吧。您的肯定对我来说是最大的动力！！</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/components/%E5%A4%84%E7%90%86%E4%BA%8B%E4%BB%B6/" rel="next" title="处理事件">
          处理事件
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/The%20Object%20Model/%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%EF%BC%88compute%20properties%EF%BC%89/" rel="prev" title="计算属性（compute properties）">
            计算属性（compute properties）
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%EF%BC%8C%E4%BC%A0%E9%80%92%E5%8F%82%E6%95%B0%E5%88%B0%E7%BB%84%E4%BB%B6%E4%B8%8A"><span class="toc-text">1，传递参数到组件上</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2%EF%BC%8C%E4%BD%8D%E7%BD%AE%E5%8F%82%E6%95%B0"><span class="toc-text">2，位置参数</span></a></li></ol></li></ol></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '属性传递', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
